<?php

/**
 * This file is part of the Codizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Codizer Core Team <team@codizer.org>
 * @package     Codizer
 */

abstract class f_core_View
{
	private $model;

	abstract public function execute();

	/**
	 * set the model document(s)
	 *
	 * @param mixed $model
	 * @return f_core_View
	 */
	public function setModel($model)
	{
		$this->model = $model;
		return $this;
	}

    /**
     * get all models
     *
     * @return array
     */
    public function getModels()
    {
        return $this->model;
    }
	
	/**
	 * @return mixed
	 */
	public function getModel($key = null)
	{
		if(!is_null($key) && is_array($this->model) && isset($this->model[$key]))
		{
			return $this->model[$key];
		}
		else if(!is_null($key) && !isset($this->model[$key]))
		{
			return null;
		}		
		
		return $this->model;
	}
	
	/**
	 * Return an instance of f_template_Template
	 *
	 * @return f_template_AbstractTemplate
	 */
	public function getTemplateEngine()
	{
		return f_template_Template::getInstance();
	}

	/**
	 * Return view module name
	 * @return string
	 */
	public function getModuleName()
	{
	   $reflection = new ReflectionObject($this);
	   $vars = explode("_", $reflection->getName());
	   return $vars[1];
	}

	/**
	 * Generic method to render a view with model
	 * @param string $templateName
	 * @param boolean $withCache
	 */
	public function renderView($templateName, $withCache = false, $cacheDiscriminator = null, $cacheGroup = null, $debugMode = true)
	{
	    $tplEngine = $this->getTemplateEngine();

	    if($withCache === false)
	    {
            $tplEngine = $tplEngine->disableCache();
	    }

        if(!is_null($cacheDiscriminator))
        {
            $tplEngine->addCacheDiscriminator($cacheDiscriminator);
        }

        if(!is_null($cacheGroup))
        {
            $tplEngine->setCacheGroup($cacheGroup);
        }

	    $tplEngine->setModuleTemplate($this->getModuleName(), $templateName);

	    if(is_array($this->model) && count($this->model) > 0)
	    {
		foreach($this->model as $varName => $value)
		{
		    $tplEngine->assign($varName, $value);
		}
	    }

	    $tplEngine->renderDisplay($debugMode);
	}
	
	/**
	 * Get the current session instance
	 *
	 * @return f_core_Session
	 */
	public function getSession()
	{
		return f_core_Session::getInstance();
	}	
}